<?php

namespace App\Services\Core\Store\ZongheInsur;

use Prophecy\Exception\Exception;
use App\Helpers\Http\HttpCurl;
use App\Models\Factory\UserFactory;
use App\Models\Factory\InsuranceFactory;
use App\Models\Factory\IdentityFactory;

/**
 * 综合意外险对接
 * Class ZongheInsurService
 * @package App\Services\Core\Store\ZongheInsur
 */
class ZongheInsurService
{


    /**
    * 综合意外险投保
    *
    * @param $data
    */ 
    public static function push($data)
    {

        // 声明投保信息
        $idcard = (isset($data['idcard'])) ? $data['idcard'] : '';
        $Insurdata = array(
                            "name"     => $data['name'],
                            "birthday" => $data['birthday'],
                            "sex"      => $data['sex'],
                            "phone"    => $data['phone'],
                            "idcard"   => $idcard,
                            "ip"       => $data['ip'],
                            "c"        => ZongheInsurConfig::$merchantId,
                            "p"        => ZongheInsurConfig::$positionId,
                            "v"        => self::setSignature($data['birthday'],$data['phone'])
                          );
        // 投保请求
        $result = HttpCurl::i()->GET(ZongheInsurConfig::$url, $Insurdata);
        $insu = json_decode($result,true);
        // 投保成功添加用户保险信息
        if($insu['success'] == "true"){

            $user_id    = $data['uid'];
            $brandname  = $insu['brandName'];
            $bxproid    = $insu['prodId'];
            $bxtypename = $insu['bxtypeName'];
            $bxexpire   = $insu['bxExpire'];
            $bxarticle  = serialize($insu['bxArticle']);
            $resulturl  = $insu['resultUrl'];

            //更新用户昵称、生日、性别字段
            $udata  = array('nickname' => $data['name'], 'birthday' => strtotime($data['birthday']),'sex' => $data['sex'] );
            $upres  = UserFactory::setIdentity($user_id,$udata);
            $uiden  = array('name' => $data['name'], 'sex' => $data['sex'] );
            $upiden = IdentityFactory::setIden($user_id,$uiden);
            //投保成功，将信息入库，并返回相关信息
            $inseres = InsuranceFactory::insertinsurance($brandname,$bxproid,$user_id,$bxtypename,$bxexpire,$bxarticle,$resulturl);

            //获取受保人和保险产品
            $insurance = InsuranceFactory::getinsuByuserid($user_id);
            $nickname  = $insurance['nickname'];
            $proname   = $insurance['proname'];
            $insu['nickname'] = $nickname;
            $insu['proname'] = $proname;

        }
        return $insu;
    }

    /**
    * 综合意外险签名生成
    * 
    */ 
    public static function setSignature($birthday,$phone)
    {
        return md5($birthday.$phone.ZongheInsurConfig::$key_md5.ZongheInsurConfig::$merchantId.ZongheInsurConfig::$positionId);
    }    


}
